import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_acrylic/flutter_acrylic.dart';
import 'package:system_theme/system_theme.dart';
import 'application/configuration/configs.dart';
import '/core/core.dart';
import 'package:window_manager/window_manager.dart';
import 'package:windows_single_instance/windows_single_instance.dart';

import 'application/application.dart';

void main(List<String> args) {
  runZonedGuarded(() async {
    setupGlobalErrorHandler();
    await initializeBeforeAppLaunch(args);

    runApp(const Application());
  }, onError);
}

void setupGlobalErrorHandler() {
  FlutterError.onError = (details) {
    Zone.current.handleUncaughtError(
      details.exception,
      details.stack ?? StackTrace.current,
    );
  };
}

Future<void> initializeBeforeAppLaunch(args) async {
  WidgetsFlutterBinding.ensureInitialized();
  await WindowsSingleInstance.ensureSingleInstance(args, 'online.shupian.fnos.tv', onSecondWindow: (args) {});
  await Core.initialize();
  await Configs.initialize();
  if (!kIsWeb &&
      [
        TargetPlatform.windows,
        TargetPlatform.android,
      ].contains(defaultTargetPlatform)) {
    SystemTheme.accentColor.load();
  }

  if (Core.isDesktop) {
    await Window.initialize();
    if (defaultTargetPlatform == TargetPlatform.windows) {
      await Window.hideWindowControls();
    }
    await WindowManager.instance.ensureInitialized();
    windowManager.waitUntilReadyToShow().then((_) async {
      await windowManager.setTitle('飞牛影视 ${Core.version}');
      await windowManager.setTitleBarStyle(
        TitleBarStyle.hidden,
        windowButtonVisibility: false,
      );
      await windowManager.setMinimumSize(const Size(500, 600));
      await windowManager.show();
      await windowManager.setPreventClose(true);
      await windowManager.setSkipTaskbar(false);
    });
  }


}

void onError(Object error, StackTrace? stackTrace) {
  if (kDebugMode) {
    print('Uncaught Error: $error');
    if (stackTrace != null) {
      print('Uncaught Error StackTrace: \n$stackTrace');
    }
  }
}
